package com.hm.oauth.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.hm.common.common.BeanUtil;
import com.hm.common.common.CommonUtil;
import com.hm.common.common.EncryptUtil.Md5;
import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.model.PageInfo;
import com.hm.oauth.model.QUserModel;
import com.hm.oauth.model.UserModel;
import com.hm.oauth.model.UserModel.ExtensionNature;
import com.hm.oauth.repository.UserRepository;
import com.hm.oauth.vo.UserVo;
import com.hm.oauth.vo.UserVo.ExtensionNatureVo;
import com.mysema.query.types.expr.BooleanExpression;

/**
 * @author shishun.wang
 * @date 下午2:19:54 2016年8月30日
 * @version 1.0
 * @describe
 */
@Component
public class UserService {

	private static final Logger logger = LoggerFactory.getLogger(UserService.class);

	@Autowired
	private UserRepository userRepository;

	public String add(UserVo userVo) {
		QUserModel qUserModel = QUserModel.userModel;

		if (CommonUtil.isNotEmpty(userVo.getName())) {
			BooleanExpression pageable = qUserModel.name.eq(userVo.getName());
			Iterator<UserModel> iterator = userRepository.findAll(pageable).iterator();
			while (iterator.hasNext()) {
				throw ServiceException.warn("该用户名已存在,请重新选择");
			}
		}

		if (CommonUtil.isNotEmpty(userVo.getPhone())) {
			BooleanExpression pageable = qUserModel.phone.eq(userVo.getPhone());
			Iterator<UserModel> iterator = userRepository.findAll(pageable).iterator();
			while (iterator.hasNext()) {
				throw ServiceException.warn("该电话号码已存在,请重新选择");
			}
		}

		if (CommonUtil.isNotEmpty(userVo.getEmail())) {
			BooleanExpression pageable = qUserModel.email.eq(userVo.getEmail());
			Iterator<UserModel> iterator = userRepository.findAll(pageable).iterator();
			while (iterator.hasNext()) {
				throw ServiceException.warn("该邮箱已存在,请重新选择");
			}
		}

		UserModel model = new UserModel();
		{
			model = (UserModel) BeanUtil.copyProperties(model, userVo);

			List<ExtensionNature> natures = new ArrayList<ExtensionNature>();
			if (!CollectionUtils.isEmpty(userVo.getNatures())) {
				userVo.getNatures().forEach(nature -> {
					natures.add((ExtensionNature) BeanUtil.copyProperties(new ExtensionNature(), nature));
				});
			}
			model.setPassword(Md5.getMD5Code(userVo.getPassword()));
			model.setNatures(natures);
		}
		return userRepository.save(model).getId();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public PageInfo<UserVo> query(int pageNo, int pageSize) {
		PageInfo<UserVo> pageInfo = new PageInfo<UserVo>(pageNo, pageSize);

		Pageable pageable = new QPageRequest(pageInfo.getPageNumber(), pageInfo.getPageSize(),
				QUserModel.userModel.createTime.desc());
		BooleanExpression predicate = QUserModel.userModel.state.eq(1);

		List<UserVo> vos = new ArrayList<UserVo>();
		Page page = userRepository.findAll(predicate, pageable);
		page.getContent().forEach(userModel -> {
			UserVo userVo = (UserVo) BeanUtil.copyProperties(new UserVo(), userModel);

			List<ExtensionNatureVo> natures = new ArrayList<ExtensionNatureVo>();
			if (!CollectionUtils.isEmpty(((UserModel) userModel).getNatures())) {
				((UserModel) userModel).getNatures().forEach(nature -> {
					natures.add((ExtensionNatureVo) BeanUtil.copyProperties(new ExtensionNatureVo(), nature));
				});
			}
			userVo.setNatures(natures);

			vos.add(userVo);
		});

		return pageInfo.execute(page, vos);
	}

	public UserVo get(String id) {
		UserModel userModel = userRepository.findOne(id);
		if (null == userModel) {
			logger.debug("don't find {} user info", id);
			throw ServiceException.warning(ErrorCode.DATA_NOT_FOUND, id);
		}

		UserVo userVo = (UserVo) BeanUtil.copyProperties(new UserVo(), userModel);
		List<ExtensionNatureVo> natures = new ArrayList<ExtensionNatureVo>();
		if (!CollectionUtils.isEmpty(((UserModel) userModel).getNatures())) {
			((UserModel) userModel).getNatures().forEach(nature -> {
				natures.add((ExtensionNatureVo) BeanUtil.copyProperties(new ExtensionNatureVo(), nature));
			});
		}
		userVo.setNatures(natures);

		return userVo;
	}

	public String delete(String id) {
		UserModel userModel = userRepository.findOne(id);
		if (null == userModel) {
			logger.debug("don't find {} user info", id);
			throw ServiceException.warning(ErrorCode.DATA_NOT_FOUND, id);
		}
		userModel.setState(0);
		return userRepository.save(userModel).getId();
	}

	public UserVo login(String username, String password) {
		UserModel userModel = userRepository.findOne(QUserModel.userModel.name.eq(username));

		if (null == userModel) {
			logger.debug("don't find {} user info ,name is ", username);
			throw ServiceException.warning(ErrorCode.DATA_NOT_FOUND, username);
		}
		if (Md5.getMD5Code(password).equals(userModel.getPassword())) {
			UserVo userVo = (UserVo) BeanUtil.copyProperties(new UserVo(), userModel);
			List<ExtensionNatureVo> natures = new ArrayList<ExtensionNatureVo>();
			if (!CollectionUtils.isEmpty(((UserModel) userModel).getNatures())) {
				((UserModel) userModel).getNatures().forEach(nature -> {
					natures.add((ExtensionNatureVo) BeanUtil.copyProperties(new ExtensionNatureVo(), nature));
				});
			}
			userVo.setNatures(natures);
			return userVo;
		} 
		else {
			logger.debug("{} try login system ,but password is waring , login fail", username);
			throw ServiceException.warn(username + ",密码错误");
		}
	}
}
